package org.example.paymentservice.service.provider.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.paymentservice.config.PaymentProperties;
import org.example.paymentservice.service.provider.PaymentProvider;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Map;

@Slf4j
@Component("alipay")
@RequiredArgsConstructor
public class AliPayProvider implements PaymentProvider {
    private final AlipayClient alipayClient;
    private final PaymentProperties paymentProperties;

    @Override
    public String processPayment(BigDecimal amount, Map<String, String> paymentDetails) {
        try {
            AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
            request.setNotifyUrl(paymentProperties.getAliPay().getNotifyUrl());
            request.setReturnUrl(paymentProperties.getAliPay().getReturnUrl());

            Map<String, Object> bizContent = new HashMap<>();
            bizContent.put("out_trade_no", paymentDetails.get("orderNo"));
            bizContent.put("total_amount", amount.toString());
            bizContent.put("subject", paymentDetails.get("description"));
            bizContent.put("buyer_id", paymentDetails.get("buyerId"));
            request.setBizContent(JsonUtil.toJson(bizContent));

            AlipayTradeCreateResponse response = alipayClient.execute(request);
            
            if (response.isSuccess()) {
                return response.getTradeNo();
            } else {
                throw new RuntimeException("AliPay payment failed: " + response.getSubMsg());
            }
        } catch (AlipayApiException e) {
            log.error("AliPay payment processing failed", e);
            throw new RuntimeException("Payment processing failed", e);
        }
    }

    @Override
    public boolean validatePayment(String transactionId) {
        try {
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            Map<String, Object> bizContent = new HashMap<>();
            bizContent.put("out_trade_no", transactionId);
            request.setBizContent(JsonUtil.toJson(bizContent));

            AlipayTradeQueryResponse response = alipayClient.execute(request);
            
            return response.isSuccess() && "TRADE_SUCCESS".equals(response.getTradeStatus());
        } catch (AlipayApiException e) {
            log.error("AliPay payment validation failed", e);
            return false;
        }
    }

    @Override
    public String processRefund(String transactionId, BigDecimal amount, String reason) {
        try {
            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
            Map<String, Object> bizContent = new HashMap<>();
            bizContent.put("out_trade_no", transactionId);
            bizContent.put("refund_amount", amount.toString());
            bizContent.put("refund_reason", reason);
            request.setBizContent(JsonUtil.toJson(bizContent));

            AlipayTradeRefundResponse response = alipayClient.execute(request);
            
            if (response.isSuccess()) {
                return response.getTradeNo();
            } else {
                throw new RuntimeException("AliPay refund failed: " + response.getSubMsg());
            }
        } catch (AlipayApiException e) {
            log.error("AliPay refund processing failed", e);
            throw new RuntimeException("Refund processing failed", e);
        }
    }
}